#!/bin/sh
clear

#++++++++++++++++++++ ++++++++++++++++++++++++++
#whereis 'infreemeeting'
#sudo apt purge 'infreemeeting'

remoteUser=uos
remotePwd=123qwe
ListFiles=ip.txt
localFiles=infreeMeeting.uos.amd64.2.0.1.deb
RunDir=$(cd $(dirname $0);pwd)
remoteDir=/home/uos/Desktop
remoteIP=192.168.1.117
cmd2="echo '123qwe' | sudo -S apt install /home/uos/Desktop/infreeMeeting.uos.amd64.2.0.1.deb -y"	#安装软件
#cmd2="echo '123qwe' | sudo -S apt remove infreemeeting"	#卸载无纸化软件

#++++++++++++++++++++ 2 获取当前系统的密码++++++++++++++++++++++++++
read -p "请输入当前系统密码(本地):" LocalPwd
if ! type nmap >/dev/null 2>&1;then echo $LocalPwd | sudo -S apt install nmap -y;fi
if ! type expect >/dev/null 2>&1;then echo $LocalPwd | sudo -S apt install expect -y;fi

# 1.获取网络中开启了22号端口的IP地址和密码的集合
read -p "请输入要扫描的IP段(如192.168.1):" IPDuan
echo "正在扫描开启了22号端口的ip"
nmap -p 22 $IPDuan | grep -oP "([0-9]{1,3}\.){3}[0-9]{1,3}" >./ip.txt			#I要扫描的IP段，根据实际情况修改
sed -i "s/$/&:$remotePwd/g" ./ip.txt				# 在扫描出来的IP地址后面加上密码
LocalIP=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}')	#获取本机IP地址,便于后面删除列表中的自己
sed -i /^"${LocalIP}"/d ./ip.txt	#删除列表中的本机IP地址,避免SSh时,操作到本机
cat ./ip.txt

#--------------------------------------------------------------
for line in $(cat $RunDir/$ListFiles)
do
    ip=$(echo "$line"|cut -f1 -d":")	#取ip.txt文件中的ip地址
    TempPwd=$(echo "$line"|cut -f2 -d":")	#取ip.txt文件中的密码
echo $RunDir/$localFiles
echo $ip
echo $TempPwd

expect <<EOF
set timeout -1
spawn scp -r ${RunDir}/${localFiles} ${remoteUser}@${ip}:${remoteDir}
#spawn ssh -t ${remoteUser}@${remoteIP} echo 123qwe | sudo -S $remoteDir/$localFiles
expect {
	"yes/no" {send "yes\r"; exp_continue}
	"password:" {send "${TempPwd}\r"}
}
expect 100%
expect eof
EOF
done
#--------------------------------------------------------------
for line in $(cat $RunDir/$ListFiles);
do
ip=$(echo "$line"|cut -f1 -d":")	#取ip.txt文件中的ip地址
TempPwd=$(echo "$line"|cut -f2 -d":")	#取ip.txt文件中的密码
expect -c "
    spawn ssh $remoteUser@$ip $cmd2
    expect {
        \"(yes/no)\" {send \"yes\r\"; exp_continue}
        \"password:\" {send \"$TempPwd\r\"; exp_continue}
        #\"root@*\" {send \"free -m\r exit\r\"; exp_continue}
    }"
done
